<?php

namespace App\Http\Middleware;

use App\Models\Member;
use App\Models\SettingWechat;
use Closure;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class CheckOpenid
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            $SettingWechat = SettingWechat::first();
            $Wechat = Factory::officialAccount([
                'app_id' => $SettingWechat->wechat_appid,
                'secret' => $SettingWechat->wechat_secret
            ]);
            $_openid = Member::where("id",auth('member')->id())->value('openid');
            $Wechat->user->get($_openid);
            return $next($request);
        } catch (\Exception $e) {
            auth('member')->logout();
            return response(['message'=>'WechatError'], 401);
        }
    }
}
